package com.zsy._14并发包_异步回调;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 异步回调：使用
 * <p>
 * CompletableFuture 类
 * <p>
 * 方法介绍：
 * 1. runAsync() 无返回值的异步回调
 * 2. supplyAsync() 有返回值的异步回调
 * 3. whenComplete() 正常回调方法
 * 4. exceptionally() 异常回调方法
 * 5. get() 获取异步回调执行完成后的结果
 *
 * @author: zhangshuaiyin
 * @date: 2021/8/25 21:08
 */
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // testRunAsync();
        testSupplyAsync();
    }

    /**
     * 没有返回结果的异步回调 - runAsync
     *
     * @throws ExecutionException   e
     * @throws InterruptedException e
     */
    public static void testRunAsync() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "runAsync=>Void");
        });

        System.out.println("1111");

        // 获取阻塞执行结果
        completableFuture.get();
    }

    /**
     * 有返回结果的异步回调 - supplyAsync
     *
     * @throws ExecutionException   e
     * @throws InterruptedException e
     */
    public static void testSupplyAsync() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
            int i = 10 / 0;
            return 1024;
        });
        // 正常回调
        completableFuture.whenComplete((t, u) -> {
            System.out.println("t=>" + t); // 正常时返回正常的返回结果，异常时为null
            System.out.println("u=>" + u); // 正常时为null，异常时返回错误信息：java.util.concurrent.CompletionException:java.lang.ArithmeticException: /byzero
        }).exceptionally((e) -> { // 异常回调
            System.out.println(e.getMessage());
            // 异常时的返回结果
            return 233;
        });

        System.out.println(completableFuture.get());
    }
}
